package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.GetPhotosAdapter;
import com.cardbaobao.cardbabyclient.ui.dialog.PhotosDirDialog;
import com.cardbaobao.cardbabyclient.model.ImageFolder;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.BitmapUtil;
import com.cardbaobao.cardbabyclient.utils.ScreenUtil;
import com.cardbaobao.cardbabyclient.utils.SharedPreferencesUtil;
import com.cardbaobao.cardbabyclient.utils.TakePhotoUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 获取手机相册图片、拍照
 *
 * @author zad
 */
public class GetPictureActivity extends BaseActivity implements OnClickListener, PhotosDirDialog.OnImageDirSelectedListener, AdapterView.OnItemClickListener {
    public static final String PIC_PATH="picture_url";

    public static final String CANT_CHOOSE_PIC_B ="cant_choose_pic";

    @BindView(R.id.title_bar)
    TitleBar titleBar;

    /**
     * 存储文件夹中的图片数量
     */
    private int mPicsSize;
    /**
     * 当前图片路径文件夹
     */
    private File mImgCurrentDir;
    /**
     * 当前目录下所有的图片
     */
    private List<String> mDirImages;
    /**
     * 显示图片网格
     */
    @BindView(R.id.id_gv_photos)
    GridView mGirdView;

    @BindView(R.id.rl_bottom)
    RelativeLayout rlBottom;
    /**
     * 照片适配器
     */
    private GetPhotosAdapter mPhotosAdapter;
    /**
     * 临时的辅助类，用于防止同一个文件夹的多次扫描
     */
    private HashSet<String> mDirPaths = new HashSet<>();
    /**
     * 扫描拿到所有的图片文件夹
     */
    private List<ImageFolder> mImageFolders = new ArrayList<>();
    /**
     * 当前选中的文件夹目录
     */
    @BindView(R.id.id_tv_dir)
    TextView mChooseDir;
    /**
     * 显示当前目录下的图片数
     */
    @BindView(R.id.id_tv_count)
    TextView mImageCount;
    /**
     * 当前图片文件夹所存在的文件数量
     */
    int totalCount = 0;
    /**
     * 要获取的图片类型
     */
    private String[] imgTypes = {".jpg", ".png", "jpeg"};
    /**
     * 拍照回调码
     */
    public static final int TAKE_PICTURE = 0x0000;
    /**
     * 截图回调码
     */
    public static final int CROP_PICTURE = 0x0101;
    /**
     * 图片目录列表对话框
     */
    private PhotosDirDialog mPhotosDirDialog;
    /**
     * 裁剪图片压缩大小64kb
     */
    private static final int DEFAULT_COMPRESS_SIZE = 64;
    /**
     * 默认要裁剪的图片宽度
     */
    private static int DEFAULT_IMG_WIDTH;
    /**
     * 默认要裁剪的图片高度
     */
    private static int DEFAULT_IMG_HEIGHT;
    /**
     * 裁剪照片保存路径
     */
    private static final String DEFAULT_CROP_PICTURE_PATH = TakePhotoUtil.FILE_PIC_SCREENSHOT.getAbsolutePath() + File.separator + "crop_image.jpg";

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            dismissProgressDialog();
            // 为View绑定数据
            data2View();
        }
    };

    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarDarkFont(true, Constant.STATUS_BAR_FONT_ALPHA).init();
        titleBar.setLeftViewOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mGirdView.setOnItemClickListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        //创建裁剪图片存放文件夹
        TakePhotoUtil.createFileScreenshots();
        if(getIntent().getBooleanExtra(CANT_CHOOSE_PIC_B,false)){
            mDirImages = new ArrayList<>();
            mDirImages.add("");
            mPhotosAdapter = new GetPhotosAdapter(this, mDirImages, R.layout.layout_photos_gridview_item, "");
            mGirdView.setAdapter(mPhotosAdapter);
            rlBottom.setVisibility(View.GONE);
        }else{
            getImages();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_get_photos;
    }

    @Override
    protected void onResume() {
        super.onResume();
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.getApplicationContext().getString(R.string.event_0x017));
    }

    /**
     *  为View绑定数据
     */
    private void data2View() {
        if (mImgCurrentDir == null) {
            ToastUtil.showToast("未扫描到任何图片");
            return;
        }
        mDirImages = new ArrayList<>();
        mDirImages.add("");
        List<String> mTempImgList = Arrays.asList(mImgCurrentDir.list());// 获取最多图片文件中的图片集合
        for (String img : mTempImgList) {
            img = img.toLowerCase();
            if (img.endsWith(imgTypes[0]) || img.endsWith(imgTypes[1]) || img.endsWith(imgTypes[2])) {
                mDirImages.add(img);
            }
        }

        totalCount = mDirImages.size() - 1;
        /**
         * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
         */
        mPhotosAdapter = new GetPhotosAdapter(this, mDirImages, R.layout.layout_photos_gridview_item, mImgCurrentDir.getAbsolutePath());
        mGirdView.setAdapter(mPhotosAdapter);
        rlBottom.setVisibility(View.VISIBLE);
        mImageCount.setText(totalCount + "张");
        mChooseDir.setText("/" + mImgCurrentDir.getName());
    }

    /**
     *  利用ContentProvider扫描手机中的图片，此方法在运行在子线程中 完成图片的扫描，最终获得jpg最多的那个文件夹
     */
    private void getImages() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            ToastUtil.showToast("请确认是否存在SD卡");
            return;
        }
        // 显示进度条
        showProgressDialog(false, "载入中...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = mContext.getContentResolver();
                // 只查询jpeg和png的图片
                Cursor mCursor = mContentResolver.query(mImageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"image/jpeg",
                        "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);
                if(mCursor!=null){
                    while (mCursor.moveToNext()) {
                        // 获取图片的路径
                        String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                        if(!path.contains(TakePhotoUtil.FILE_PIC_SCREENSHOT.getAbsolutePath())){//过滤掉裁剪图片文件夹
                            // 拿到第一张图片的路径
                            if (firstImage == null) firstImage = path;
                            // 获取该图片的父路径名
                            File parentFile = new File(path).getParentFile();
                            if (parentFile == null) continue;
                            String dirPath = parentFile.getAbsolutePath();
                            ImageFolder imageFolder;
                            // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                            if (mDirPaths.contains(dirPath)) {
                                continue;
                            } else {
                                mDirPaths.add(dirPath);
                                // 初始化imageFolder
                                imageFolder = new ImageFolder();
                                imageFolder.setDir(dirPath);
                                imageFolder.setFirstImagePath(path);
                            }

                            String[] pics = parentFile.list(new FilenameFilter() {
                                @Override
                                public boolean accept(File dir, String filename) {
                                    filename = filename.toLowerCase();
                                    return filename.endsWith(imgTypes[0]) || filename.endsWith(imgTypes[1]) || filename.endsWith(imgTypes[2]);
                                }
                            });
                            int picSize=pics==null?0:pics.length;
                            totalCount += picSize;
                            imageFolder.setCount(picSize);
                            mImageFolders.add(imageFolder);
                            if (picSize > mPicsSize) {
                                // 如果此文件夹的图片数量大于前一个文件夹，则此文件夹为默认选中的文件夹
                                mPicsSize = picSize;
                                mImgCurrentDir = parentFile;
                            }
                        }
                    }
                    mCursor.close();
                }
                // 扫描完成，辅助的HashSet也就可以释放内存了
                mDirPaths = null;
                // 通知Handler扫描图片完成
                mHandler.sendEmptyMessage(0x110);

            }
        }).start();

    }

    @OnClick(R.id.rl_bottom)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_bottom://底部弹出dialog
                if(mImgCurrentDir!=null){
                    if (mPhotosDirDialog == null) {
                        mPhotosDirDialog = new PhotosDirDialog(mContext, mImageFolders, "/" + mImgCurrentDir.getName());
                        mPhotosDirDialog.setOnImageDirSelectedListener(this);
                    }
                    mPhotosDirDialog.show();
                }
                break;
        }
    }

    /**
     *  底部弹出选择菜单单击回调事件
     */
    @Override
    public void onImageDirSelected(ImageFolder imageFolder) {
        mImgCurrentDir = new File(imageFolder.getDir());
        if (mDirImages != null) {
            mDirImages.clear();
            mDirImages.add("");
        }
        mDirImages.addAll(Arrays.asList(mImgCurrentDir.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                //文件过滤
                filename = filename.toLowerCase();
                if (filename.endsWith(imgTypes[0]) || filename.endsWith(imgTypes[1]) || filename.endsWith(imgTypes[2])) return true;
                return false;
            }
        })));
        /**
         * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
         */
        mPhotosAdapter = new GetPhotosAdapter(this, mDirImages, R.layout.layout_photos_gridview_item, mImgCurrentDir.getAbsolutePath());
        mGirdView.setAdapter(mPhotosAdapter);
        mImageCount.setText(imageFolder.getCount() + "张");
        mChooseDir.setText(imageFolder.getName());
        mPhotosDirDialog.dismiss();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TAKE_PICTURE) {
                try {
                    compressImage(TakePhotoUtil.FILE_PIC_SCREENSHOT.getAbsolutePath() + File.separator + TakePhotoUtil.getLocalTakeImageFileName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == CROP_PICTURE) {
                //图片裁剪回调
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    Bitmap cropBitmap = bundle.getParcelable("data");
                    if (saveCropImage(cropBitmap)) {
                        gotoResult(DEFAULT_CROP_PICTURE_PATH);
                    }else{
                        gotoResult(SharedPreferencesUtil.CbbInfo.getPicturePath());
                    }
                }else{
                    gotoResult(SharedPreferencesUtil.CbbInfo.getPicturePath());
                }
            }
        }
    }


    /**
     *  将参数带回上一页
     *
     * @param imgPath 本地图片路径
     */
    private void gotoResult(String imgPath) {
        Intent intent = getIntent();
        intent.putExtra(PIC_PATH, imgPath);
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 图片单击事件
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            //拍照
            TakePhotoUtil.takePhoto(mContext, GetPictureActivity.TAKE_PICTURE);//调用系统拍照方法
        } else {
            compressImage(mImgCurrentDir.getAbsolutePath() + File.separator + mDirImages.get(position));
        }
    }

    /**
     * 压缩图片并返回上一页
     * @param imgPath
     */
    private void compressImage(String imgPath){
        if(DEFAULT_IMG_WIDTH == 0||DEFAULT_IMG_HEIGHT==0){
//            DEFAULT_IMG_WIDTH = ScreenUtil.getScreenWidth(mContext) / 2;
            DEFAULT_IMG_WIDTH = ScreenUtil.getScreenWidth(mContext);
            DEFAULT_IMG_HEIGHT=ScreenUtil.getScreenHeight(mContext);
        }
        Bitmap bitmap = BitmapUtil.getSmallBitmap(imgPath,DEFAULT_IMG_WIDTH,DEFAULT_IMG_HEIGHT);
        if(saveCropImage(bitmap)){
            gotoResult(DEFAULT_CROP_PICTURE_PATH);
        }
    }

    /**
     *  保存裁剪过的图片
     */
    private boolean saveCropImage(Bitmap mBitmap) {
        if (mBitmap == null) return false;
        mBitmap = BitmapUtil.compressImage(mBitmap, DEFAULT_COMPRESS_SIZE);//尽量将图片压缩到64k
        if (mBitmap == null) return false;
        File imageFile = new File(DEFAULT_CROP_PICTURE_PATH);
        if (imageFile.exists()) {
            imageFile.delete();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(imageFile);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}
